/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights
 * reserved. <a>http://www.cqcis.com</a>
 */
package com.cqcis.uip.base.framework.core.impl;

import org.apache.commons.httpclient.HttpMethod;

import com.cqcis.uip.base.framework.common.HttpClient;
import com.cqcis.uip.base.framework.common.Task;
import com.cqcis.uip.base.framework.core.RegisteredServiceContext;
import com.cqcis.uip.base.framework.handlers.HttpClientService;

/**
 * @author huangmy
 * @date   2008-10-13
 */
public class HttpClientTaskContextAdaptor extends AbstractClientTaskContextAdaptor<Object> implements HttpClientService {
    private HttpClientTaskContextWriter writer;
	
	@Override
	protected AbstractTaskContext<Object> createTaskContext(
			RegisteredServiceContext serviceContext, Task task) {	
		AbstractTaskContext<Object> taskContext = new AbstractHttpClientTaskContext(serviceContext, task) {
			@Override
			protected void doHttpClientWrite(Task task, HttpMethod method) throws Exception {
				if (writer != null) {
					writer.doHttpClientTaskContextWrite(task, method);
				}
			}
		};
		return taskContext;
	}
	
	public void doMessageReceived(HttpMethod method, Task task)
			throws Exception {
		super.messageSyncReceived(method, task);
	}
	
	public HttpMethod doMessageSend(HttpClient hc, Task task) throws Exception {
		task.setAttribute(AbstractHttpClientTaskContext.HTTPCLIENT, hc);
		return (HttpMethod) super.messageSyncSend(task);
	}
	
	/**
	 * 正常结束，通过该种方式支持在ClientBlockingService中没有进行任何操作就结束的情况
	 * 
	 */
	@Override
	protected void afterNormalFinished(Task task) {
		if (this.writer != null) {
			this.writer.afterNormalFinished(task);
		}
		super.afterNormalFinished(task); 
	}
	
	@Override
	protected void notifyCommitEnd(Task task) {
	}

	public static interface HttpClientTaskContextWriter {
		/**
		 * write
		 * 
		 * @param task
		 * @param method
		 */
		public void doHttpClientTaskContextWrite(Task task, HttpMethod method) throws Exception;
		
		/**
		 * 正常结束
		 * 
		 */
		public void afterNormalFinished(Task task);
	}

	public void setWriter(HttpClientTaskContextWriter writer) {
		this.writer = writer;
	}
}
